<template>
  <tm-app class="app-container">
    <tm-navbar :title="workTitle"></tm-navbar>
    <view>
      <tm-tabs
        showTabsLineAni
        :list="workStatus"
        :item-width="180"
        :default-name="currentStatus"
        :active-name="currentStatus"
        active-color="#366EF4"
        :width="750"
        :showTabsLine="true"
        @change="tabChanged"
      >
      </tm-tabs>
      <tm-sheet :padding="[0]" :margin="[0]">
        <scroll-view
          class="detailForm-wrap"
          :show-scrollbar="false"
          :scroll-x="true"
          :scroll-y="true"
        >
          <view class="table-header">
            <view
              v-for="(col, index) in tableList.header"
              :key="index"
              class="header-cell"
              :style="{
                width: cellWidth*2 + 'rpx',
                backgroundColor: col.opts?.color || '#f5f5f5'
              }"
            >
              {{ col.name }}
            </view>
          </view>
          <!-- 分割线 -->
          <view class="divider"></view>
          <!-- 表格内容 -->
          <view class="table-body">
            <template v-if="tableList.data && tableList.data.length > 0">
              <view
                v-for="(row, rowIndex) in tableList.data"
                :key="rowIndex"
                class="table-row"
                @click="handleRowClick(row)"
              >
                <view
                  v-for="(col, colIndex) in tableList.header"
                  :key="colIndex"
                  class="table-cell"
                  :style="{ width: cellWidth*2 + 'rpx' }"
                >
                  {{ formatFieldValue(col.field, row[col.field])}}
                </view>
              </view>
            </template>
            <view v-else class="empty-data">
              <text>暂无数据</text>
            </view>
          </view>
        </scroll-view>
      </tm-sheet>
      <view class="btn-container">
        <tm-button
          :shadow="0"
          block
          disabledColor="#B5C7FF"
          fontColor="#fff"
          :margin="[0]"
          :padding="[0, 0]"
          :height="100"
          @click="handleSubmit"
        >
          <text style="font-size: 28rpx">办事发起</text>
        </tm-button>
      </view>
    </view>
  </tm-app>
</template>

<script lang="ts" setup>
import { ref, computed,watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import orgCtrl from '@/ts/controller'
import { WorkTask } from '@/ts/core/work/task';
import { getWidget } from '@/utils/work'
import { model } from '@/ts/base';
const params = ref()
const apply = ref()
const workTitle = ref('办事名称')
// 定义列表状态
const workStatus = [
  { key: 'draft', title: '草稿箱' },
  { key: 'started', title: '已发起' },
  { key: 'finished', title: '已完结' }
]
// 当前选中的状态
const currentStatus = ref('draft')
const cellWidth = ref(160)
// 表格配置
const getTableConfig = computed(() => {
  const baseColumns = ['id','title', 'remark']
  const headOpts = {
    opts: {
      color: '#f5f5f5'
    }
  }
  const baseHeader = [
    { field: 'id', name: '唯一标识', ...headOpts },
    { field: 'title', name: '标题', ...headOpts },
    { field: 'remark', name: '备注', ...headOpts }
  ]
  // 默认配置
  const defaultConfig = {
    header: baseHeader,
    data: [],
    fields: {
      columns: baseColumns
    }
  }
  if (!apply.value) {
    return defaultConfig
  }
  if (currentStatus.value === 'draft') {
    return {
      header: [
        ...baseHeader,
        ...(apply.value?.primaryForms?.[0]?.fields?.map(field => ({
          field: field.id,
          name: field.name,
          ...headOpts
        })) ?? [])
      ],
      data: [],
      fields: {
        columns: [
          ...baseColumns,
          ...(apply.value?.primaryForms?.[0]?.fields?.map(f => f.id) ?? [])
        ]
      }
    }
  } else {
    return {
      header: [
        ...baseHeader,
        { field: 'content', name: '内容' },
        { field: 'status', name: '状态' },
        ...(apply.value?.primaryForms?.[0]?.fields?.map(field => ({
          field: field.id,
          name: field.name,
          ...headOpts
        })) ?? [])
      ],
      data: [],
      fields: {
        columns: [
          ...baseColumns,
          'content',
          'status',
          ...(apply.value?.primaryForms?.[0]?.fields?.map(f => f.id) ?? [])
        ]
      }
    }
  }
})
// 监听配置变化
watch(
  [getTableConfig, () => currentStatus.value],
  ([newConfig]) => {
    tableList.value = {
      ...newConfig,
      data: tableList.value?.data || []
    }
  },
  { immediate: true }
)
const tableList = ref(getTableConfig.value)
onLoad(options => {
  if (!options) return
  if (!options.id) return
  if (options) {
    try {
      // 解码并解析参数
      const parsedData = options
      params.value = parsedData // 存储参数
      uni.showLoading({ title: '加载中...' })
      searchWork()
    } catch (error) {
      console.error('解析参数错误:', error)
    }
  }
})

// 状态切换处理
const tabChanged = async (tabkey: string) => {
  currentStatus.value = tabkey
  await loadWorkList()
}
// 加载列表数据
const loadWorkList = async () => {
  uni.showLoading({ title: '加载中...' })
  try {
    // 根据不同状态获取数据
    let data
    let workData
    let request: any = {
      userData: [],
      options: {
        project: {
          data: 0
        },
        match: {
          defineId: apply.value.metadata.defineId
        },
        sort: {
          createTime: -1
        }
      }
    }

    switch (currentStatus.value) {
      case 'draft':
        // 获取草稿箱数据
        data = await orgCtrl.user.workStagging.loadResult(request)
        break
      case 'started':
        // 获取已发起数据
        data = await orgCtrl.work.loadTasks({
          userData: [],
          options: {
            match: {
              createUser: orgCtrl.user.id,
              defineId: apply?.value.define.id,
              status: {
                _lt_: 100
              },
              nodeId: {
                _exists_: false
              }
            },
            sort: {
              createTime: -1
            }
          }
        })
        if (data.success && !Array.isArray(data.data)) {
          data.data = [];
        }
        if (data) {
          const lastData = await Promise.all(
            data.data.map(async (val) => {
              const work = new WorkTask(val, orgCtrl.work.user, true);
              await work.loadInstance();
              const instanceData = work.instanceData;
              return { ...val, ...instanceData?.primary };
            }),
          );
          workData = lastData || [];
        }
        break
      case 'finished':
        // 获取已完结数据
        data = await orgCtrl.work.loadTasks({
          userData: [],
          options: {
            match: {
              createUser: orgCtrl.user.id,
              defineId: apply?.value.define.id,
              status: {
                _gte_: 100
              },
              nodeId: {
                _exists_: false
              }
            },
            sort: {
              createTime: -1
            }
          }
        })
        if (data.success && !Array.isArray(data.data)) {
          data.data = [];
        }
        if (data) {
          const lastData = await Promise.all(
            data.data.map(async (val) => {
              const work = new WorkTask(val, orgCtrl.work.user, true);
              await work.loadInstance();
              const instanceData = work.instanceData;
              return { ...val, ...instanceData?.primary };
            }),
          );
          workData = lastData || [];
        }
        break
    }
    if (currentStatus.value === 'draft') {
      tableList.value.data = (data?.data || []).map((item: any) => ({
        title: item.name || item.title,
        remark: item.remark || '-',
        ...item // 保留原有的字段数据
      }))
    } else {
      tableList.value.data = (workData || []).map((item: any) => ({
        title: item.name || item.title,
        content: item.content || '-',
        remark: item.remark || '-',
        ...item
      }))
    }
  } catch (error) {
    console.error('加载列表失败:', error)
    uni.showToast({ title: '加载失败', icon: 'error' })
  } finally {
    uni.hideLoading()
  }
}
// 添加状态转换函数
const getStatusText = (status: number) => {
  switch (status) {
    case 1:
      return '审核中'
    case 100:
      return '通过'
    case 200:
      return '驳回'
    case 240:
      return '流程重置'
    default:
      return '-'
  }
}
const getFullPath = (lookups: model.XLookup[], targetValue: string): string => {
  const valueNode = lookups.find(item => item.value === targetValue)
  if (!valueNode) return ''

  const path: string[] = [valueNode.text]
  let currentNode = valueNode
  
  while (currentNode.parentId) {
    const parentNode = lookups.find(item => item.id === currentNode.parentId)
    if (!parentNode) break
    path.unshift(parentNode.text)
    currentNode = parentNode
  }
  
  return path.join('/')
}
const formatFieldValue = (field: string, value: any) => {
  if(field==='status') return getStatusText(value)
  if(['id', 'title', 'remark', 'content'].includes(field)) {
    return value || '-'
  }
  
  // 查找字段定义
  const fieldDef = apply.value?.primaryForms?.[0]?.fields?.find(f => f.id === field)
  if (!fieldDef) return value || '-'

  // 根据字段类型处理
  switch(getWidget(fieldDef.valueType,fieldDef.widget)) {
    case '数字框':
    case '文本框':
    case '多行文本框':
    case '日期选择框':
    case '时间选择框':
      return value || '-'
    case '单选框':
    case '选择框':
      return fieldDef.lookups!.find(v => v.value === value)?.text
    case '人员搜索框':
      return orgCtrl.user.findShareById(value)?.name
    case '多级选择框':
      return getFullPath(fieldDef.lookups!, value) || '-'
    default:
      return value || '-'
  }
}
// 处理表格行点击
const handleRowClick = async(row: any) => {
  if(currentStatus.value === 'draft'){
    let data = row;
    const res = await orgCtrl.user.workStagging.find([row.id]);
    if (res.length > 0) {
      data = res[0];
    }
    uni.navigateTo({
      url: '/pages/open/work?id=' +
      params.value.id +
      '&belongId=' +
      params.value.belongId +
      '&targetId=' +
      params.value.targetId,
      success: function (res) {
        res.eventChannel.emit('workData', {
          type: 'draft',
          data: row.id,
          content: row.remark,
          instance:data
        })
      }
    })
  }else if(currentStatus.value === 'started'){
    uni.navigateTo({
      url: '/pages/work-pages/detail',
      success: res => {
        res.eventChannel.emit('workDetail', [{id: row.id,type:'已发起'}])
      }
    })
  }else if(currentStatus.value ==='finished'){
    uni.navigateTo({
      url: '/pages/work-pages/detail',
      success: res => {
        res.eventChannel.emit('workDetail', [{id: row.id,type:'已完结'}])
      }
    })
  }
}
const searchWork = async () => {
  if (!params.value) return
  const fileData = await orgCtrl.searchWork(
    params.value.belongId,
    params.value.id
  )
  apply.value = await fileData!.createApply(undefined, undefined)
  uni.hideLoading()
  await loadWorkList()
}
const handleSubmit = () => {
  //发起办事 跳转页面
  uni.navigateTo({
    url: '/pages/open/work?id=' +
    params.value.id +
    '&belongId=' +
    params.value.belongId +
    '&targetId=' +
    params.value.targetId,
    success: function (res) {
      res.eventChannel.emit('workData', {
        type: 'create',
        data: undefined
      })
    }
  })
}
</script>

<style scoped>
.app-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #fff;
}

.btn-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 10rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  height: 140rpx;
}
.table-header {
  display: flex;
  flex-direction: row;
  white-space: nowrap;
}

.header-cell {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-shrink: 0;
}

.divider {
  height: 2rpx;
  background-color: #eee;
  margin: 0;
}
.table-body {
  width: 100%;
}

.table-row {
  display: flex;
  flex-direction: row;
  border-bottom: 1rpx solid #eee;
}

.table-cell {
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-shrink: 0;
}
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200rpx;
  color: #999;
  font-size: 28rpx;
}
</style>
